import datetime
from pathlib import Path

import akshare as ak
import pandas as pd


def get_recent_trade_dates(N=10):
    today = datetime.date.today()
    trade_date_df = ak.tool_trade_date_hist_sina()
    trade_date_list = trade_date_df["trade_date"].astype(str).tolist()

    # 找到最近的交易日
    while str(today) not in trade_date_list:
        today -= datetime.timedelta(days=1)

    end_index = trade_date_list.index(str(today))
    start_index = max(0, end_index - N + 1)
    recent_dates = trade_date_list[start_index:end_index + 1]

    return recent_dates


def find_hottest_sector():
    excel_names = get_recent_trade_dates()  # 假设返回日期列表
    excel_dict = {}

    for date_str in excel_names:
        file_path = Path(f"../excel/{date_str}.xlsx")

        if not file_path.is_file():
            print(f"文件 {file_path} 不存在，跳过")
            continue

        try:
            data = pd.read_excel(file_path)
            for row in data.itertuples():
                sector_name = row.名称  # 通过属性访问列
                excel_dict[sector_name] = excel_dict.get(sector_name, 0) + 1
        except Exception as e:
            print(f"读取文件 {file_path} 时出错: {e}")

    # 将字典转换为DataFrame并排序
    result_df = pd.DataFrame.from_dict(excel_dict, orient='index', columns=['count'])
    return result_df.sort_values(by='count', ascending=False)


num_statics = find_hottest_sector()
print(num_statics)
